<template>
  <div class="alarm">
    <selectbutton
      :buttonselectlist="buttonselectlist"
      @nowselectbuttonindex="nowselectbuttonindex"
    />
    <div v-if="nowselectbutton === 0" class="alarm-config">
      <div class="search-item-list">
        <div class="search-item">
          <div class="label">生长品种名称：</div>
          <div v-if="plantVarityList.length <= 8" class="value">
            <el-button
              v-for="(item, index) in plantVarityList"
              :key="index"
              type="info"
              plain
              size="mini"
              :class="{ active: plantVarietyNo == item.plantVarietyNo }"
              @click="choosePlantVarity(item)"
              >{{ item.plantVarietyName }}</el-button
            >
            <!-- shwang@casdelta.com -->
          </div>
          <div v-if="plantVarityList.length > 8" class="value">
            <el-select
              v-model="plantVarietyObj"
              value-key="plantVarietyNo"
              @change="choosePlantVarity"
            >
              <el-option
                v-for="(item, index) in plantVarityList"
                :key="index"
                :label="item.plantVarietyName"
                :value="item"
              />
            </el-select>
          </div>
        </div>
        <div class="search-item">
          <div class="label">生长阶段名称：</div>
          <div class="value">
            <el-button
              v-for="(item, index) in growthStageList"
              :key="index"
              type="info"
              plain
              size="mini"
              :class="{ active: growthPhaseNo == item.growthPhaseNo }"
              @click="chooseGrowthStage(item)"
              >{{ item.growthPhaseName }}</el-button
            >
          </div>
        </div>
      </div>
      <div class="top">
        <Title title="配置环境条件" size="big" />
        <!-- <div> -->
        <el-row class="input-hang-all">
          <el-col :span="24">
            <!-- <div
                v-for="(item, indexA) in alarmTemplateList"
                :key="indexA + 'name'"
                class="alar-name"
            >-->
            <el-row class="input-hang">
              <el-col :span="3" style="text-align: right">预警名称：</el-col>
              <el-col :span="4">
                <el-input
                  v-model="formData.environmentMonitorName"
                  placeholder="请输入预警名称"
                  style="width: 100%;margin-left: 1%;"
                  @input="changeShow"
                />
              </el-col>
              <el-col :span="3" style="text-align: right">
                <span style=" color: red;margin-right: 4px;">*</span>
                选择物联数据类型：</el-col
              >
              <el-col :span="4" style="text-align: right">
                <el-select
                  v-model="formData.dataTypeId"
                  placeholder="请选择物联数据类型"
                  style="width: 100%"
                  @input="changeShow"
                >
                  <el-option
                    v-for="kit in dataTypeList"
                    :key="kit.dataTypeId"
                    :label="kit.dataTypeName"
                    :value="kit.dataTypeId"
                  />
                </el-select>
              </el-col>
            </el-row>
            <el-row class="input-hang">
              <el-col :span="3" style="text-align: right">上限：</el-col>
              <el-col :span="4" style="text-align: right">
                <el-input
                  v-model="formData.maxValue"
                  placeholder="请输入上限"
                  style="width: 100%;margin-left: 1%;"
                  @input="changeShow"
                />
              </el-col>
              <el-col :span="3" style="text-align: right">造成的结果：</el-col>
              <el-col :span="4" style="text-align: right">
                <el-input
                  v-model="formData.resultForHigh"
                  placeholder="请输入内容"
                  @change="changeShow"
                />
              </el-col>
            </el-row>
            <el-row class="input-hang">
              <el-col :span="3" style="text-align: right">下限：</el-col>
              <el-col :span="4" style="text-align: right">
                <el-input
                  v-model="formData.minValue"
                  style="width: 100%;;margin-left: 1%;"
                  placeholder="请输入下限"
                  @input="changeShow"
                />
              </el-col>
              <el-col :span="3" style="text-align: right">造成的结果：</el-col>
              <el-col :span="4">
                <el-input
                  v-model="formData.resultForLow"
                  placeholder="请输入内容"
                  @change="changeShow"
                />
              </el-col>
            </el-row>
            <!-- </div> -->
          </el-col>
        </el-row>
        <!-- <p class="error-info">dasdasdasdasdasda</p> -->
        <div class="alarm-hang">
          <div class="left-alarm">
            <div class="alarm-icon-big">预警条件预览：</div>
            <li>{{ showAlarmLine }} {{ causeResult }}</li>

            <div class="submit-btns">
              <el-button
                v-if="judgePermission(9, 'add')"
                alt
                class="btns"
                size="small"
                type="primary"
                plain
                @click="addConfig()"
                >{{
                  formData.environmentMonitorNo ? "确认修改" : "确认添加"
                }}</el-button
              >
              <el-button
                src="~@/assets/conservation-model/back.png"
                alt
                class="btns"
                size="small"
                type="primary"
                plain
                @click="cancel"
                >取消</el-button
              >
            </div>
          </div>
        </div>
        <!-- </div> -->
      </div>
      <div class="bottom">
        <Title title="已添加环境数据预警" size="big" />
        <!-- <div class="title-con"> -->
        <div
          v-for="(item, index) in alarmConfigList"
          :key="index"
          class="alarm-hang"
        >
          <div class="left-alarm" @click="environmentMonitor(item)">
            <div class="alarm-icon">{{ item.environmentMonitorName }}</div>
            <li>
              当{{ item.dataTypeName }}大于{{ item.maxValue }}时，可能造成{{
                item.resultForHigh
              }}； {{ item.dataTypeName }}低于{{ item.minValue }}时，可能造成{{
                item.resultForLow
              }}
            </li>
          </div>
          <div class="handle-btns">
            <!-- <div class="edit" @click="edit(index)">修改</div> -->
            <div
              v-if="judgePermission(9, 'delete')"
              class="del"
              @click="dels(item.environmentMonitorNo)"
            >
              删除
            </div>
          </div>
          <!-- </div> -->
        </div>
      </div>
    </div>
    <div v-else class="alarm-config">
      <div class="search-item-list">
        <div class="search-item">
          <div class="label">批次名称：</div>
          <div class="value">
            <el-input v-model="batchName" clearable @input="search" />
          </div>
          <div class="label" style="margin-left: 10px">生长品种名称：</div>
          <div v-if="plantVarityList.length <= 8" class="value">
            <el-button
              v-for="(item, index) in plantVarityList"
              :key="index"
              type="info"
              plain
              size="mini"
              @click="searchs(item.plantVarietyNo)"
              >{{ item.plantVarietyName }}</el-button
            >
            <!-- shwang@casdelta.com -->
          </div>
          <div v-if="plantVarityList.length > 8" class="value">
            <el-select v-model="varietyNo" clearable @change="search">
              <el-option
                v-for="(item, index) in plantVarityList"
                :key="index"
                :label="item.plantVarietyName"
                :value="item.plantVarietyNo"
              />
            </el-select>
          </div>
          <div class="value" style="margin-left: 10px">
            <StartTimeEndTimeSelectionBox
              @startVal="startVal"
              @endVal="endVal"
            />
          </div>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="batchName" label="批次名称" />
        <el-table-column prop="batchNo" label="批次号" />
        <el-table-column prop="plantVarietyName" label="种养品种" />
        <el-table-column
          prop="computeDate"
          label="计算时间"
          :formatter="dateFormat"
        />
        <el-table-column width="120" label="计算结果">
          <template v-if="scope.row.monitorRecordNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="monitorRsee(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </div>
    <el-dialog
      title="查看详细预警"
      :visible="causeDialogVisible"
      class="dialogRec"
      :before-close="
        () => {
          causeDialogVisible = false;
        }
      "
    >
      <div class="facility-list">
        <div
          v-for="(item, index) in conBTNList"
          :key="index"
          class="facility-item"
        >
          <div class="info-line">
            <div class="name">
              关联设施：{{ item.facilityName }} 物联数据读取时间 :
              {{ item.startDate }}~{{ item.endDate }}
            </div>
            <!-- <div class="info-line"><div class="name">设施名称：</div><div class="value">{{ item.facilityName }}</div></div> -->
            <div
              v-for="(items, indexs) in item.detailResultList"
              :key="indexs"
              class="value"
            >
              <span>
                当前{{ items.dataTypeName }} : {{ items.currentValue
                }}{{ items.unit }}
              </span>
              <span>
                适宜 {{ items.dataTypeName }} : {{ items.expectMinValue
                }}{{ items.unit }}~{{ items.expectMaxValue }}{{ items.unit }}
              </span>
              <span>{{ items.result }}</span>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="causeDialogVisible = false"
            >关 闭</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from "@/components/Title/index";
import plantApi from "@/api/basic-info-manage/category-management";
import alarmTemplateApi from "@/api/digital-production/monitoring-alarm/alarm-template-configuration";
import alarmConfigApi from "@/api/digital-production/conservation-model/alarm-config";
import api from "@/api/digital-production/crop-model/growth-features-manage";
import selectbutton from "./selectbutton/index";
import StartTimeEndTimeSelectionBox from "./StartTimeEndTimeSelectionBox";
import Pagination from "@/components/Pagination";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "environment-alarm-config",
  components: {
    Title,
    selectbutton,
    Pagination,
    StartTimeEndTimeSelectionBox
  },
  mixins: [mymixin],
  props: {},
  data() {
    return {
      alarmConfigList: [],
      showAlarmLine: "",
      alarmTemplateList: [
        {
          dataTypeId: "",
          upList: [],
          downList: [],
          upValue: "",
          downValue: ""
        }
      ], // 选择告警名称（多个告警）
      getalarmTemList: [], // 告警名称数组
      plantVarietyNo: "", // 选择品种
      causeResult: "", // 造成的结果
      plantingTypeIdList: [], // 选择品种数组,

      plantVarityList: [], // 品种列表
      growthStageList: [], // 生长阶段
      // plantVarietyNo: null,
      plantVarietyObj: {},
      growthStageNo: null,
      dataTypeList: [],
      causeDialogVisible: false,
      formData: {},
      buttonselectlist: [
        {
          name: "环境预警配置"
        }
        // {
        //   name: "环境数据自动计算"
        // }
      ],
      nowselectbutton: 0,
      growthPhaseNo: "",
      batchName: "",
      varietyNo: "",
      batchFacilityMapperList: [],
      conBTNList: [],
      startTime: "",
      endTime: ""
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    this.getSetect();
    // this.queryPlantingType();
    this.queryAlarmTemplate();
    this.getTableDataList();
  },
  methods: {
    nowselectbuttonindex(e) {
      this.nowselectbutton = e;
    },
    // 获取数值告警表格数据
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          batchName: this.batchName || undefined,
          organizationNo: sessionStorage.organizationNo,
          varietyNo: this.varietyNo || undefined,
          startTime: this.startTime || undefined,
          endTime: this.endTime || undefined
        }
      };
      alarmConfigApi.getDataItemtable(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 搜索
    searchs(e) {
      this.currentPage = 1;
      this.plantVarietyNo = e || undefined;
      this.varietyNo = e || undefined;
      this.search();
    },
    // 搜索
    search() {
      this.currentPage = 1;
      // this.plantVarietyNo = e || undefined
      // this.varietyNo = e || undefined
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSelectionChange(list) {},
    // 搜索框时间
    startVal(e) {
      this.startTime = e;
      this.getTableDataList();
    },
    endVal(e) {
      this.endTime = e;
      this.getTableDataList();
    },
    // 显示预览的数据
    changeShow() {
      this.showAlarmLine = "";
      this.causeResult = "";
      let datas = "";
      let data = this.formData.environmentMonitorName || "" + ": 当";
      // this.alarmTemplateList.forEach((item, listIndex) => {
      let index = this.dataTypeList.findIndex(
        a => a.dataTypeId === this.formData.dataTypeId
      );
      // console.log(item, this.dataTypeList)

      if (index !== -1) {
        this.formData.dataTypeName = this.dataTypeList[index]["dataTypeName"];
        data = data + this.dataTypeList[index]["dataTypeName"];
        if (this.formData.maxValue) {
          data =
            data +
            "大于" +
            this.formData.maxValue +
            (this.formData.resultForHigh
              ? `时, ${this.formData.resultForHigh};`
              : `;`);
        }
        // if (this.formData.resultForHigh) {
        //   data = data + "<=" + this.formData.maxValue + "时，"
        // }
        datas = datas + this.dataTypeList[index]["dataTypeName"];
        if (this.formData.minValue) {
          datas =
            datas +
            "低于" +
            this.formData.minValue +
            (this.formData.resultForLow
              ? `时, ${this.formData.resultForLow};`
              : `;`);
        }
        // if (this.formData.resultForLow) {
        //   data = data + "<=" + this.formData.maxValue + "时，" + this.formData.resultForLow;
        // }
      }
      // if (listIndex < this.alarmTemplateList.length - 1) {
      //   data = data + ",";
      // }
      // });
      // console.log(data)
      // data = data;
      this.showAlarmLine = data;
      this.causeResult = datas;
    },
    // 时间转换
    dateFormat(row, colnum) {
      if (row.monitorRecordNo) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    // 查询种养类型
    queryPlantingType() {
      plantApi.querybycondition().then(res => {
        if (res.code === 1) {
          let data = res.data;
          // 赋值数组
          this.plantingTypeIdList = data;
          if (this.$route.query) {
            this.plantVarietyNo = this.$route.query.plantVarietyNo;
            this.queryHave();
          }
        } else {
          // this.$message.error(res.msg);
        }
      });
    },
    // 忘了
    environmentMonitor(e) {
      this.formData = { ...e };
      this.changeShow();
    },
    // 下拉框
    async getSetect() {
      const { data: plant } = await api.queryWithPhaseByCondition();
      this.plantVarityList = plant;
      api.getalldatalist().then(res => {
        this.dataTypeList = res.data;
      });
      this.choosePlantVarity(this.plantVarityList[0]);
    },
    async choosePlantVarity(val) {
      // this.getTableDataList()
      this.plantVarietyNo = val.plantVarietyNo;
      const { data: plant } = await api.queryPlantNo({
        plantVarietyNo: val.plantVarietyNo
      });
      this.growthStageList = plant;
      this.chooseGrowthStage({
        growthPhaseNo: this.growthStageList[0].growthPhaseNo
      });
    },
    chooseGrowthStage(val) {
      this.growthPhaseNo = val.growthPhaseNo;
      this.queryHave();
    },
    async choosePlantVaritys(val) {
      // this.getTableDataList()
      this.plantVarietyNo = val;
      const { data: plant } = await api.queryPlantNo({ plantVarietyNo: val });
      this.growthStageList = plant;
    },
    monitorRsee(e) {
      // eslint-disable-next-line no-undef
      this.conBTNList = JSON.parse(e.result) || [];
      this.causeDialogVisible = true;
    },
    // 查询告警模板
    queryAlarmTemplate() {
      alarmTemplateApi.getlist({ page: 1, size: 10000 }).then(res => {
        if (res.code === 1) {
          let data = res.data || {};
          let content = data.content || [];
          // 赋值数组
          this.getalarmTemList = content;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 改变种养类型，查询已经添加的数据
    changePlant() {
      if (this.plantVarietyNo) {
        this.queryHave();
      }
    },
    // 查询已经添加的数据
    queryHave() {
      let params = {
        growthPhaseNo: this.growthPhaseNo,
        organizationNo: sessionStorage.getItem("organizationNo")
      };
      if (this.plantVarietyNo) {
        alarmConfigApi.queryByOrganizationIdAndType(params).then(res => {
          if (res.code === 1) {
            let data = res.data || [];
            // 赋值数组
            this.alarmConfigList = data;
          } else {
            this.$message.error(res.msg);
          }
        });
      } else {
        this.$message.error("请选择种养类型！");
      }
    },
    // 添加环境数据预警
    addConfig() {
      if (!this.formData.dataTypeId) {
        return this.$message.warning("请先选择数据类型");
      }
      if (!this.formData.environmentMonitorNo) {
        let params = {
          ...this.formData,
          plantVarietyNo: this.plantVarietyNo,
          growthPhaseNo: this.growthPhaseNo,
          organizationNo: sessionStorage.getItem("organizationNo")
        };
        alarmConfigApi.add(params).then(res => {
          if (res.code === 1) {
            this.$message.success("环境数据预警添加成功！");
            this.formData = {};

            this.showAlarmLine = "";
            this.causeResult = "";
            this.queryHave();
          } else {
            if (res.msg.includes("数据类型已配置")) {
              this.$message.error("该数据类型已配置");
            } else {
              this.$message.error("环境数据预警添加失败！");
            }
          }
        });
      } else {
        alarmConfigApi.edit(this.formData).then(res => {
          if (res.code === 1) {
            this.$message.success("环境数据预警修改成功！");
            this.showAlarmLine = "";
            this.causeResult = "";
            this.formData = {};
            this.queryHave();
          } else {
            this.$message.error("环境数据预警修改失败！");
          }
        });
      }
    },
    back() {
      this.$router.push({ name: "Configuration" });
    },
    addalarmTemplate() {
      this.alarmTemplateList.push({
        dataTypeId: "",
        upList: [],
        downList: [],
        upValue: "",
        downValue: ""
      });
    },
    delalarmTemplate(index) {
      this.alarmTemplateList.splice(index, 1);
    },
    // edit(index) {
    //   this.showAlarmLine = this.alarmConfigList[index];
    //   this.alarmTemplateList = this.showAlarmLine.alarmTemplateList;
    //   this.plantVarietyNo = this.showAlarmLine.plantVarietyNo;
    //   this.causeResult = this.showAlarmLine.causeResult;
    // },
    dels(data) {
      this.$confirm("确认是否删除预警数据？")
        .then(_ => {
          alarmConfigApi.del(data).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryHave();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(_ => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.alarm-config {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  .search-item-list {
    height: 100px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .search-item {
      height: 30px;
      line-height: 30px;
      display: flex;
      margin-bottom: 10px;
    }
  }
  .top {
    height: 35%;
    width: 100%;
    overflow: hidden;
    background-color: rgba(0, 57, 71, 1);
    box-shadow: 0px 0px 32px inset rgba(24, 140, 158, 0.8);
  }
  .bottom {
    height: calc(64% - 120px);
    width: 100%;
    overflow-y: auto;
    margin-top: 5px;
    background-color: rgba(0, 57, 71, 1);
    box-shadow: 0px 0px 32px inset rgba(24, 140, 158, 0.8);
  }
}
.title-con {
  overflow-y: scroll;
}
.error-info {
  padding: 10px 30px;
  color: red;
  font-size: 14px;
}
.alarm {
  height: 100%;
  width: 100%;
  position: relative;
  overflow: hidden;
}
.alarm-hang {
  width: 98%;
  margin: 0 auto;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #fff;
  font-size: 18px;
  padding: 10px;
  background: linear-gradient(
    90deg,
    rgba(7, 90, 105, 1) 0%,
    rgba(7, 90, 105, 0.5) 47.48%,
    rgba(7, 90, 105, 1) 100%
  );
  .left-alarm {
    width: 100%;
    display: flex;
    align-items: center;
    position: relative;

    > li {
      list-style: none;
      width: 81%;
    }
    // .btns {
    //   position: absolute;
    //   right: 0px;
    // }
  }

  .alarm-icon-big {
    color: rgba(5, 235, 219, 1);
    font-size: 18px;
    margin-right: 10px;
    padding: 10px 15px;
    position: relative;
    // width: 100%;
  }
  .alarm-icon {
    background: url("~@/assets/conservation-model/shape.png") center center
      no-repeat;
    background-size: 100% 100%;
    color: rgba(5, 235, 219, 1);
    font-size: 14px;
    padding: 10px 15px;
    margin-right: 10px;
  }
}
.handle-btns {
  // display: flex;
  width: 50px;
  > div {
    cursor: pointer;
    font-size: 14px;
    // margin: 5px;
    color: rgba(5, 235, 219, 1);
    &:first-child {
      padding: 0 10px 0 0;
      &:hover {
        color: red;
        font-weight: 700;
        font-size: 16px;
      }
    }
  }
}
.alar-name {
  width: 100%;
}
// .btns {
//   padding: 0 10px;
// }
.input-hang {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-bottom: 5px;
  // s
}
.input-hang-all {
  padding: 14px 0;
  display: flex;
  align-items: flex-start;
}
.submit-btns {
  // width: 100%;
  text-align: center;
  position: absolute;
  right: 0;
}
.value {
  ::v-deep {
    .el-button {
      border: 1.5px solid #33eadc;
    }
    .el-button--info.is-plain {
      color: #ffffff;
      background: initial;
      border-color: #71bdd5;
    }
  }
}
.active {
  color: #33eadc !important;
  background: initial;
  box-shadow: inset 0px 0px 6px 0px #33eadc !important;
  border-color: #33eadc !important;
}
::v-deep .el-table {
  max-height: 78%;
  height: 78%;
}
::v-deep .el-button--info.is-plain:focus,
.el-button--info.is-plain:hover {
  color: #33eadc;
  background: initial;
  box-shadow: inset 0px 0px 6px 0px #33eadc;
  border-color: #33eadc;
}
.facility-list {
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
  .facility-item {
    width: 100%;
    margin-right: 3%;
    margin-bottom: 10px;
    // height: 80px;
    border-radius: 5px;
    // border: 1px solid #ccc;
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.15);
    padding: 10px 20px;

    .info-line {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      font-size: 14px;
      flex-direction: row;
      flex-wrap: wrap;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
      .name {
        text-align: left;
        width: 100%;
        flex-shrink: 0;
        font-size: 20px;
        font-weight: 500;
      }
      .value {
        width: 100%;
        text-align: left;
        font-weight: normal;
        margin: 10px 0;
        font-size: 16px;
        span {
          display: inline-block;
          &:nth-child(1) {
            width: 25%;
          }
          &:nth-child(2) {
            width: 25%;
          }
          &:nth-child(3) {
            width: 25%;
          }
        }
      }
    }
  }
}
// .value {
//   ::v-deep {

//   }
// }
</style>
